package top.mhtools.pigeon.ding.service.support;

import com.google.common.collect.ImmutableMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import top.mhtools.pigeon.common.enums.SendTypeEnum;
import top.mhtools.pigeon.common.factory.MessageFactory;
import top.mhtools.pigeon.common.factory.ding.DingMessageFactory;
import top.mhtools.pigeon.common.factory.wechat.WeChatMessageFactory;
import top.mhtools.pigeon.common.persistence.SendMessageRequest;
import top.mhtools.pigeon.common.persistence.SimpleSendMessageReqDTO;
import top.mhtools.pigeon.common.service.SendMessageService;

import java.util.Map;
import java.util.Optional;

/**
 * 简单消息发送适配通用消息发送
 *
 * @author machen
 * @date 2020/6/17 10:38
 */
@Service
public class SendMessageServiceAdapter implements SimpleSendMessageService {

    @Value("${sendType.default}")
    private String sendTypeDefault;

    @Autowired
    private SendMessageService sendMessageService;

    @Override
    public void simpleSendMessage(SimpleSendMessageReqDTO simpleSendMessageReqDTO) {
        SendMessageRequest sendMessageRequest = buildMessageRequest(simpleSendMessageReqDTO);
        sendMessageService.sendMessage(sendMessageRequest);
    }

    private static final Map<String, MessageFactory> messageFactoryMap =
            new ImmutableMap.Builder<String, MessageFactory>()
                    .put(SendTypeEnum.DING_TALK.getName(), new DingMessageFactory())
                    .put(SendTypeEnum.WE_CHAT.getName(), new WeChatMessageFactory())
                    .build();

    private SendMessageRequest buildMessageRequest(SimpleSendMessageReqDTO simpleSendMessageReqDTO) {
        String sendTypeVal = checkSendTypeReturnValue(simpleSendMessageReqDTO.getSendType());
        MessageFactory messageFactory = messageFactoryMap.get(sendTypeVal);
        SendMessageRequest messageRequest = messageFactory.getSendType().buildMessage(simpleSendMessageReqDTO);
        return messageRequest;
    }

    private String checkSendTypeReturnValue(String sendType) {
        return Optional.ofNullable(sendType).orElse(sendTypeDefault);
    }
}
